<?php
class Pageley_Imaging_Shape_RoundedRectangle implements Pageley_Imaging_Shape {
    
    private $width;
    private $height;
    private $radius;
    private $roundBottom;
    private $roundTop;
    private $roundLeft;
    private $roundRight;
    
    public function __construct($width, $height, $radius, $roundTop = true, $roundRight = true, $roundBottom = true, $roundLeft = true) {
        $this->width = $width;
        $this->height = $height;
        $this->radius = $radius;
        $this->roundLeft = $roundLeft;
        $this->roundRight = $roundRight;
        $this->roundTop = $roundTop;
        $this->roundBottom = $roundBottom;
    }
    
    public function draw($brush, $resource, $x, $y) {
        $colorId = $brush->getColorId($resource);
        $radius = $this->radius;
        $width = $this->width;
        $height = $this->height;
        
        // Rounding top
        if($this->roundTop) {
            for($i = 0; $i < $radius; $i++) {
                $y1 = $y + $i;
                $offsetX = (int) (cos(asin(1 - ($i / $radius))) * $radius);
                $x1 = $this->roundLeft ? $x + $radius - $offsetX : $x;
                $x2 = $this->roundRight ? $x + $width - 1 - $radius + $offsetX : $x + $width - 1;
                imagefilledrectangle($resource, $x1, $y1, $x2, $y1, $colorId);
            }
        }
        
        // Middle rectangle
        $x1 = $x;
        $x2 = $x + $width - 1;
        $y1 = $this->roundTop ? $y + $radius: $y;
        $y2 = $this->roundBottom ? $y + $height - 1 - $radius: $y + $height - 1;
        imagefilledrectangle($resource, $x1, $y1, $x2, $y2, $colorId);
        
        // Rounding bottom
        if($this->roundBottom) {
            for($i = 1; $i <= $radius; $i++) {
                $y1 = $y + $height - 1 - $radius + $i;
                $offsetX = (int) (cos(asin($i / $radius)) * $radius);
                $x1 = $this->roundLeft ? $x + $radius - $offsetX : $x;
                $x2 = $this->roundRight ? $x + $width - 1 - $radius + $offsetX : $x + $width - 1;
                imagefilledrectangle($resource, $x1, $y1, $x2, $y1, $colorId);
            }
        }
    }
}